#!/bin/sh /etc/rc.common
# Copyright (C) 2015 OpenWrt.org
# Copyright (C) 2020 Nishant Sharma <nishant@hopbox.in>

START=89
STOP=11

USE_PROCD=1
PROG=/usr/bin/udpspeeder

validate_udpspeeder_section() {
	uci_validate_section udpspeeder udpspeeder "${1}" \
		'enabled:bool:0'		\
		'server:bool:0' 		\
		'mode:integer:0' 		\
		'mtu:integer:1250' 		\
		'timeout:integer:8'		\
		'local:string'			\
		'remote:string'			\
		'report:integer:10'		\
		'disable_obscure:bool:0'	\
		'interval:integer:0'		\
		'fec:string:20:10'		\
		'disable_fec:bool:0'		\
		'sock_buf:integer:1024'		\
		'log_level:integer:4'		\
		'decode_buf:integer:2000'	\
		'fix_latency:bool:0'		\
		'queue_len:integer:200'		
}

start_instance() {

	local section="$1"

	local server mode mtu timeout local remote report disable_obscure fifo interval fec disable_fec sock_buf queue_len \
		decode_buf sock_buf log_level enabled

	fifo="/tmp/udpspeeder-${section}.fifo"

	validate_udpspeeder_section $section || {
		echo "validation failed"
		return 1
	}

	if [ "${enabled}" -ne 1 ]
	then
		return 1
	fi

	procd_open_instance
	procd_set_param respawn
	procd_set_param stderr 1
	procd_set_param stdout 1

	procd_set_param command "${PROG}"

	if [ "${server}" -eq 1 ]
	then
		procd_append_param command -s
	else
		procd_append_param command -c
	fi

	if [ "${disable_fec}" -eq 1 ]
	then
		procd_append_param command --disable-fec
	else
		procd_append_param command --fec "${fec}"
	fi

	if [ "${fix_latency}" -eq 1 ] && [ "${mode}" -eq 0 ]
	then
		procd_append_param command --fix-latency
	fi

	if [ "${disable_obscure}" -eq 1 ]
	then
		procd_append_param command --disable-obscure
	fi

	procd_append_param command -l "${local}"
	procd_append_param command -r "${remote}"
	procd_append_param command --mode "${mode}"
	procd_append_param command --report "${report}"
	procd_append_param command --interval "${interval}"
	procd_append_param command --mtu "${mtu}"
	procd_append_param command --sock-buf "${sock_buf}"
	procd_append_param command --decode-buf "${decode_buf}"
	procd_append_param command --queue-len "${queue_len}"
	procd_append_param command --log-level "${log_level}"
	procd_append_param command --fifo "${fifo}"
	
#	procd_set_param respawn ${respawn_threshold:-3600} ${respawn_timeout:-5} ${respawn_retry:-5}
	procd_close_instance
}

start_service() {

	config_load 'udpspeeder'
	config_foreach start_instance 'udpspeeder'

}

stop_service()
{
	service_stop ${PROG}
}

service_triggers()
{
	procd_add_reload_trigger "udpspeeder"
	procd_add_validation validate_udpspeeder_section
}
